import { Table, Modal, message } from 'antd'
import { useEffect, useState } from 'react'
import { getParentNodeAttr } from '@/api/project-flow.js'

const QuotenSelect = ({ nodeData, visible, onSuccess, onCancel}) => {
  const [data, setData] = useState([])

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      width: '10%',
      render(text, record, index) {
        return index + 1
      },
    },
    {
      title: '节点名称',
      dataIndex: 'nodeName',
      key: 'nodeName',
      width: '30%',
    },
    {
      title: '属性别名',
      dataIndex: 'attrName',
      key: 'attrName',
      width: '30%',
    },
    {
      title: '属性编码',
      dataIndex: 'attrCode',
      key: 'attrCode',
      width: '30%',
    },
  ]

  const otherTableProps = {
    tableLayout: 'fixed',
    pagination: false,
    bordered: true,
    size: 'small',
    scroll: { y: 300 }
  }

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowKeys(selectedRowKeys)
    }
  }

  const onOk = () => {
    if (selectedRowKeys.length == 0) {
      return message.warning('请选择属性')
    }
    let selectRow = data.find(item => item.key == selectedRowKeys[0])
    onSuccess(`#${selectRow.nodeName}#${selectRow.nodeId}#${selectRow.attrName}#${selectRow.attrCode}#`)
    onCancel()
  }

  useEffect(() => {
    if (visible && nodeData.nodeId) {
      getParentNodeAttr({nodeId: nodeData.nodeId}).then(({data}) => {
        const list = []
        data = data || []
        data.forEach(node => {
          node.children.forEach((attr) => {
            list.push({
              nodeId: node.id,
              nodeName: node.name,
              key: attr.id,
              attrName: attr.attr_name,
              attrCode: attr.attr_code
            })
          })
        })
        setData(list)
        setSelectedRowKeys([])
      })
    } else {
      setData([])
      setSelectedRowKeys([])
    }
  }, [visible, nodeData])

  return (
    <Modal
      centered
      title="选择引用属性"
      width={800}
      open={visible}
      onOk={onOk}
      onCancel={onCancel}
    >
      <Table
        dataSource={data}
        rowSelection={{
          selectedRowKeys,
          ...rowSelection
        }}
        columns={columns}
        {...otherTableProps}
      />
    </Modal>
  )
}

QuotenSelect.displayName = 'QuotenSelect'

export default QuotenSelect
